<template>
  <Upload
    :file-list="fileList"
    :before-upload="beforeUpload"
    :multiple="true"
    :max-count="maxCount"
    accept=".doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.txt,.rar,.zip"
    @remove="handleRemove"
  >
    <Button type="primary">
      <upload-outlined></upload-outlined>
      点击上传
    </Button>
  </Upload>
</template>
<script setup lang="ts">
  import { Upload, Button, UploadProps, message } from 'ant-design-vue';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { ref, watch } from 'vue';
  import { uploadAttachment } from '@/api/sys';

  const props = defineProps({
    modelValue: {
      type: Array as () => string[],
      default: [],
    },
    maxCount: { type: Number, default: 1 },
  });

  const emits = defineEmits(['update:modelValue']);

  const fileList = ref<UploadProps['fileList']>([]);

  watch(
    () => props.modelValue,
    (value) => {
      fileList.value = value.map((item) => JSON.parse(item));
    },
  );

  const handleRemove = (file) => {
    emits(
      'update:modelValue',
      fileList.value
        ?.filter((item) => item.uid !== file.uid)
        .map((item) =>
          JSON.stringify({
            uid: item.uid,
            name: item.name,
            url: item.url,
            fileType: item.type,
            size: item.size,
          }),
        ),
    );
  };
  const beforeUpload: UploadProps['beforeUpload'] = async (file) => {
    if (props.maxCount === fileList.value?.length) {
      message.warn(`最多上传${props.maxCount}个文件`);
      return false;
    }
    if (file.size > 50 * 1024 * 1024) {
      message.warn(`文件大小不能超过${50}M`);
      return false;
    }

    fileList.value?.push({
      name: file.name,
      status: 'uploading',
      percent: 20,
      size: file.size,
      type: file.type,
      uid: file.uid,
      url: '',
    });
    const res = await uploadAttachment({ file, filename: file.name });

    const currFile = fileList.value?.find((item) => item.uid === file.uid);
    if (!currFile) return;
    currFile.url = res.data.data.fileUrl;
    currFile.status = 'done';
    currFile.percent = 100;
    emits(
      'update:modelValue',
      fileList.value?.map((item) =>
        JSON.stringify({
          uid: item.uid,
          name: item.name,
          url: item.url,
          fileType: item.name.split('.').pop(),
          size: item.size,
        }),
      ),
    );

    return false;
  };
</script>
